import React, { useMemo, useState, useCallback } from 'react'
import * as XLSX from 'xlsx'
import { message, Table } from 'antd'

const Excel = () => {
	const [columns, setColumns] = useState([])
	const [data, setData] = useState([])
	const [dataSource, setDataSource] = useState([])
	const [excelHeader, setExcelHeader] = useState({})
	const [workBook, setWorkBook] = useState()

	// 从网络上读取某个excel文件，url必须同域，否则报错
	const onImportExcel = (file) => {
		// 获取上传的文件对象
		const { files } = file.target
		// 通过FileReader对象读取文件
		const fileReader = new FileReader()
		fileReader.onload = (event) => {
			try {
				const { result } = event.target
				// 以二进制流方式读取得到整份excel表格对象
				const workbook = XLSX.read(result, { type: 'binary' })
				setWorkBook(workbook)
				// 存储获取到的数据
				let data = []
				// 遍历每张工作表进行读取（这里默认只读取第一张表）
				for (const sheet in workbook.Sheets) {
					// esline-disable-next-line
					if (workbook.Sheets.hasOwnProperty(sheet)) {
						// 利用 sheet_to_json 方法将 excel 转成 json 数据
						data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]))
						console.log(data)
						// break; // 如果只取第一张表，就取消注释这行
					}
				}
				// 最终获取到并且格式化后的 json 数据
				message.success('上传成功！')
				setData(data)
			} catch (e) {
				// 这里可以抛出文件类型错误不正确的相关提示
				message.error('文件类型不正确！')
			}
		}
		// 以二进制方式打开文件
		fileReader.readAsBinaryString(files[0])
	}

	useMemo(() => {
		const header = data[0]
		setExcelHeader(header)
		if (header) {
			const keys = Reflect.ownKeys(header)
			keys.shift()
			const targetColumns = keys.map((item) => ({
				title: item,
				dataIndex: item,
			}))

			setColumns(targetColumns)
		}
		if (data && data.length > 0) {
			setDataSource(data.slice(0))
		}
	}, [data])

	const exportExcel = useCallback(() => {
		const targetJsonData = [].concat(excelHeader, dataSource)
		const res = XLSX.utils.json_to_sheet(targetJsonData)
		console.log(res)
		workBook.Sheets.Sheet1 = res

		const result = XLSX.writeFile(workBook, 't.xlsx')
		console.log(result)
	}, [excelHeader, dataSource])

	return (
		<div>
			<input type="file" accept=".xlsx, .xls" onChange={onImportExcel} />
			<Table columns={columns} dataSource={dataSource} rowKey={(i, t) => t} />
			<button onClick={exportExcel}>导出</button>
		</div>
	)
}

export default Excel
